package com.summli.basic.class02;

/**
 * 怎么用数组实现不超过固定大小的队列和栈？
 *
 * 栈：正常使用
 *
 * ***队列：环形数组******
 */
public class Code04_RingArray {

    private int[] num;
    private final int limit;
    private int pushi;
    private int polli;
    private int size;

    public Code04_RingArray(int l) {
        num = new int[l];
        limit = l;
        pushi = 0;
        polli = 0;
        size = 0;
    }

    public void push(int value){
        if(size==limit){
            throw new RuntimeException("栈满了，不能再添加了");
        }
        num[pushi] = value;
        size++;
        pushi = nextIndex(pushi);
    }

    private int nextIndex(int pushi) {
        return pushi < limit-1? pushi++:0;
    }

    public int poll(){
        if(size == 0){
            throw new RuntimeException("栈空了，不能弹出元素");
        }
        size--;
        int result =  num[polli];
        polli = nextIndex(polli);
        return result;
    }
    public Boolean isEmpty(){
        return size == 0;
    }
}
